package main.utils;

import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.shape.Line;
import main.entity.Raft;

import static main.utils.RiverConstants.*;
import static main.utils.TrapsFactory.getRandomTrap;

public class RiverUtils {

    public static Image newImage(String path, int width, int height) {
        return new Image(RiverUtils.class.getClassLoader().getResourceAsStream(path), width, height, false, false);
    }

    public static void forceNewTrap(Image stoneImage, GridDisplay trap) {
        trap.clear();
        trap.getDisplay().setVisible(false);

        boolean[][] newTrap = getRandomTrap();
        for (int x = 0; x < newTrap.length; x++) {
            for (int y = 0; y < newTrap[x].length; y++) {
//                trap.add(newImageView(stoneImage, newTrap[x][y]), x, y);
                trap.add(DebugUtils.newImageView(newTrap[x][y]), x, y);
            }
        }
    }

    private static ImageView newImageView(Image stoneImage, boolean visible) {
        ImageView imageView = new ImageView(stoneImage);
        imageView.setVisible(visible);
        return imageView;
    }

    public static boolean isPositionSafe(GridDisplay trap, Raft raft) {
        for (Node node : trap.getChildren()) {
            if (!node.isVisible()) {
                continue;
            }
            double barrierX = trap.getDisplay().getTranslateX() + node.getLayoutX();
            double barrierY = trap.getDisplay().getLayoutY() + node.getLayoutY();

            boolean isBarrierReachedRaft = (barrierX < RAFT_X_POSITION + RAFT_WIDTH) && (barrierX + BARRIER_SIZE > RAFT_X_POSITION);

            boolean isRaftInLineWithBarrier = raft.getY() >= barrierY && raft.getY() <= barrierY + BARRIER_SIZE;
            boolean isBarrierInLineWithRaft = barrierY >= raft.getY() && barrierY <= raft.getY() + RAFT_HEIGHT;
            boolean isOnTheSameLine = isRaftInLineWithBarrier || isBarrierInLineWithRaft;

            if (isBarrierReachedRaft && isOnTheSameLine) {
                return false;
            }
        }
        return true;
    }

    public static void movePaddle(Raft raft, boolean isRight) {
        Line paddleRight = isRight ? raft.getPaddleRight() : raft.getPaddleLeft();
        int paddleRightInitialX = isRight ? raft.getPaddleRightInitialX() : raft.getPaddleLeftInitialX();
        if (paddleRight.getEndX() == paddleRightInitialX) {
            paddleRight.setEndX(isRight ? (paddleRightInitialX - 50) : (paddleRightInitialX + 50));
        } else {
            paddleRight.setEndX(paddleRightInitialX);
        }
    }

}
